package com.thz.friend.service.blog.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.thz.common.core.constants.Constants;
import com.thz.common.core.utlis.ThreadLocalUtil;
import com.thz.friend.mapper.blog.BlogMapper;
import com.thz.friend.mapper.report.ReportMapper;
import com.thz.friend.mapper.sysuser.SysUserMapper;
import com.thz.friend.pojo.blog.Blog;
import com.thz.friend.pojo.blog.vo.BlogDetailsVO;
import com.thz.friend.pojo.blog.vo.BlogVO;
import com.thz.friend.pojo.report.Report;
import com.thz.friend.pojo.sysuser.SysUser;
import com.thz.friend.service.blog.IBlogService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author thz
 * @Date 2025/5/11
 */
@Service
public class BlogServiceImpl implements IBlogService {

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ReportMapper reportMapper;

    @Override
    public List<BlogVO> list(Long courseId) {
        List<Blog> blogList = blogMapper.selectList(new LambdaQueryWrapper<Blog>()
                .eq(Blog::getCourseId, courseId));

        List<BlogVO> blogVOList = new ArrayList<>();
        for (Blog blog : blogList) {
            BlogVO blogVO = new BlogVO();
            blogVO.setBlogId(blog.getBlogId());
            blogVO.setTitle(blog.getTitle());
            blogVO.setAuthor(sysUserMapper.selectById(blog.getCreateUser()).getNickName());
            if(blog.getContent().length()>50){
                blogVO.setContent(blog.getContent().substring(0,50));
            }
            blogVO.setContent(blog.getContent());
            blogVOList.add(blogVO);
        }
        return blogVOList;
    }

    @Override
    public BlogDetailsVO getBlogDetail(Long blogId,Long courseId) {

        // 参数校验
        if (blogId == null) {
            throw new IllegalArgumentException("博客ID不能为空");
        }

        // 调用Mapper查询数据
        Blog blog = blogMapper.selectById(blogId);
        if (blog == null) {
            throw new IllegalArgumentException("博客不存在");
        }

        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);

        Report reports = reportMapper.selectOne(new LambdaQueryWrapper<Report>()
                .eq(Report::getBlogId, blogId).eq(Report::getCreateUser,userId));

        if (reports == null) {
            Report report = new Report();
            report.setCourseId(courseId);
            report.setBlogId(blogId);
            reportMapper.insert(report);
        }

        BlogDetailsVO blogDetailsVO = new BlogDetailsVO();
        BeanUtils.copyProperties(blog, blogDetailsVO);

        return blogDetailsVO;
    }
}
